<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use think\Queue;

/**
 * 手机短信接口
 */
class Myshopifytransfer extends Api
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
        //http://121.5.76.151:100/api/Myshopifytransfer/transfer_themes?id=77
        //http://121.5.76.151:100/api/Myshopifytransfer/transfer_new_themes?oldid=7&newid=75
    }

    /**
     *  1.    * 获取主题
     */
    public function transfer_themes()
    {
        $id = $this->request->request('id');
        $result = array();
        if (!empty($id)) {
            $iscustom = Db::name('fedition_accounturl')
                ->where('id', $id)
                ->find();
            if ($iscustom) {
                $result = $this->store_isnormal($iscustom);
            }
        }
        $this->success('操作成功', $result);
    }


    /**
 1.    * 获取主题
    1.previewable 可预览 当前是否可以预览主题。
    2.processing 加工 文件是否仍在为此主题复制到位。
    3.role 角色 指定主题在商店中的使用方式。有效值：
    main : 主题已发布。客户在访问在线商店时会看到它。
    unpublished：主题未发布。客户看不到。
    demo : 该主题作为演示安装在商店中。在商家购买完整版之前无法发布主题。
    4.theme_store_id
    应用于从Shopify 主题商店主题商店安装的Shopify制作的主题的唯一标识符。并非主题商店中提供的所有主题都是由 Shopify 开发的。返回null如果商店的主题不是由Shopify发，或者如果它没有从主题商店安装。
     * 5.admin_graphql_api_id 管理员id
     */
    public function store_isnormal($iscustom)
    {
        $url = $iscustom['shopifyname'] . "/admin/api/2021-10/themes.json";
        $data = $this->geturl($url, $iscustom['shopifyapikey'], $iscustom['shopifysecretapikey']);
        $result = array();
        if ($data) {
            $data = json_decode($data, true);
            if (!empty($data['errors'])) {
                return $data['errors'];
            }
            $themes = $data['themes'];
            if (is_array($themes) && !empty($themes)) {
                //获取主题跟资产
                foreach ($themes as $theme) {
                    $transfer_themes = Db::name('transfer_themes')->where('theme_id', $theme['id'])->find();
                    if (empty($transfer_themes)) {
                        $arr['accounturl'] = $iscustom['id'];
                        $arr['theme_id'] = $theme['id'];
                        $arr['name'] = $theme['name'];
                        $arr['created_at'] = $theme['created_at'];
                        $arr['updated_at'] = $theme['updated_at'];
                        $arr['role'] = $theme['role'];
                        $arr['theme_store_id'] = $theme['theme_store_id'];
                        $arr['previewable'] = $theme['previewable'];
                        $arr['processing'] = $theme['processing'];
                        $arr['admin_graphql_api_id'] = $theme['admin_graphql_api_id'];
                        $arr['createtime'] = time();
                        $arr['updatetime'] = time();
                        $result = Db::name('transfer_themes')->insert($arr);
                        //                        if (!empty($result)) {
                        //                            $this->transfer_themes_asset($arr,$iscustom);
                        //                        }
                    }
                }
            }
        }
        return $result;
    }

    /**
        转移主题
     */
    public function transfer_new_themes()
    {
        $oldid = $this->request->request('oldid');
        $newid = $this->request->request('newid');
        $iscustom = Db::name('fedition_accounturl')
            ->where('id', $newid)
            ->find();
        $transfer_themes = Db::name('transfer_themes')
            ->where('id', $oldid)
            ->where('status', 'normal')
            ->select();
        $data = array();
        if (!empty($transfer_themes)) {
            foreach ($transfer_themes as $vtheme) {
                $url = $iscustom['shopifyname'] . "/admin/api/2021-10/themes.json";
                $theme['name'] = $vtheme['name'];
                $theme['src'] = $vtheme['src']; // zip路径
                $theme['role'] = 'unpublished';
                $theme['api_version'] = '1';
                $post['theme'] = $theme;
                if (!empty($theme['src'])) {
                    $data = $this->posturl($url, $post, $iscustom);
                    if ($data) {
                        $data = json_decode($data, true);
                        if (!empty($data['errors'])) {
                        } else {
                            $theme = $data['theme'];
                            if (!empty($theme)) {
                                //获取主题跟资产
                                $transfer_themes = Db::name('transfer_themes')->where('theme_id', $theme['id'])->find();
                                if (empty($transfer_themes)) {
                                    $arr['accounturl'] = $iscustom['id'];
                                    $arr['theme_id'] = $theme['id'];
                                    $arr['name'] = $theme['name'];
                                    $arr['created_at'] = $theme['created_at'];
                                    $arr['updated_at'] = $theme['updated_at'];
                                    $arr['role'] = $theme['role'];
                                    $arr['theme_store_id'] = $theme['theme_store_id'];
                                    $arr['previewable'] = $theme['previewable'];
                                    $arr['processing'] = $theme['processing'];
                                    $arr['admin_graphql_api_id'] = $theme['admin_graphql_api_id'];
                                    $arr['createtime'] = time();
                                    $arr['updatetime'] = time();
                                    Db::name('transfer_themes')->insert($arr);
                                }
                            }
                        }
                    }
                }
            }
        }
        $this->success('操作成功', $data);
    }

    /**
    2.  获取商品
     */
    public function transfer_product()
    {
        $id = $this->request->request('id');
        $result = array();
        if (!empty($id)) {
            $iscustom = Db::name('fedition_accounturl')
                ->where('id', $id)
                ->find();
            if ($iscustom) {
                $result = $this->product_isnormal($iscustom);
            }
        }
        $this->success('操作成功', $result);
    }

    public function product_isnormal($iscustom)
    {
        $url = $iscustom['shopifyname'] . "/admin/api/2021-10/products.json";
        $data = $this->geturl($url, $iscustom['shopifyapikey'], $iscustom['shopifysecretapikey']);
        $result = array();
        if ($data) {
            $data = json_decode($data, true);
            if (!empty($data['errors'])) {
                return $data['errors'];
            }
            $products = $data['products'];
            if (is_array($products) && !empty($products)) {
                //获取主题跟资产
                foreach ($products as $product) {
                    dump($product);
                    die;
                    $transfer_themes = Db::name('transfer_themes')->where('theme_id', $theme['id'])->find();
                    if (empty($transfer_themes)) {
                        $arr['accounturl'] = $iscustom['id'];
                        $arr['theme_id'] = $theme['id'];
                        $arr['name'] = $theme['name'];
                        $arr['created_at'] = $theme['created_at'];
                        $arr['updated_at'] = $theme['updated_at'];
                        $arr['role'] = $theme['role'];
                        $arr['theme_store_id'] = $theme['theme_store_id'];
                        $arr['previewable'] = $theme['previewable'];
                        $arr['processing'] = $theme['processing'];
                        $arr['admin_graphql_api_id'] = $theme['admin_graphql_api_id'];
                        $arr['createtime'] = time();
                        $arr['updatetime'] = time();
                        $result = Db::name('transfer_themes')->insert($arr);
                        //                        if (!empty($result)) {
                        //                            $this->transfer_themes_asset($arr,$iscustom);
                        //                        }
                    }
                }
            }
        }
        return $result;
    }

    /**
    3.  获取类别商品集合
     */
    public function transfer_custom_collections()
    {
        $id = $this->request->request('id');
        $result = array();
        if (!empty($id)) {
            $iscustom = Db::name('fedition_accounturl')
                ->where('id', $id)
                ->find();
            if ($iscustom) {
                $result[] = $this->custom_collections_isnormal($iscustom);
            }
        }
        $this->success('操作成功', $result);
    }

    public function custom_collections_isnormal($iscustom)
    {
        $url = $iscustom['shopifyname'] . "/admin/api/2021-10/custom_collections.json";
        $limit = '250';
        $url = $url . '?limit=' . $limit;
        $data = $this->geturl($url, $iscustom['shopifyapikey'], $iscustom['shopifysecretapikey']);
        $result = array();
        if ($data) {
            $data = json_decode($data, true);
            if (!empty($data['errors'])) {
                return $data['errors'];
            }
            $custom_collections = $data['custom_collections'];
            if (is_array($custom_collections) && !empty($custom_collections)) {
                //获取主题跟资产
                foreach ($custom_collections as $custom_collection) {
                    $transfer_collections = Db::name('transfer_collections')->where('collection_id', $custom_collection['id'])->find();
                    if (empty($transfer_collections)) {
                        $arr = array();
                        $arr['accounturl'] = $iscustom['id'];
                        $arr['collection_id'] = $custom_collection['id'];
                        $arr['handle'] = $custom_collection['handle'];
                        $arr['title'] = $custom_collection['title'];
                        $arr['updated_at'] = $custom_collection['updated_at'];
                        $arr['body_html'] = $custom_collection['body_html'];
                        $arr['published_at'] = $custom_collection['published_at'];
                        $arr['sort_order'] = $custom_collection['sort_order'];
                        $arr['template_suffix'] = $custom_collection['template_suffix'];
                        $arr['published_scope'] = $custom_collection['published_scope'];
                        $arr['admin_graphql_api_id'] = $custom_collection['admin_graphql_api_id'];
                        if (!empty($custom_collection['image']['src']) && isset($custom_collection['image']['src'])) {
                            $arr['image'] = $custom_collection['image']['src'];
                        }
                        $arr['createtime'] = time();
                        $arr['updatetime'] = time();
                        $result = Db::name('transfer_collections')->insert($arr);
                    }
                }
            }
        }
        return $result;
    }

    /**
     转移类别商品集合
     */
    public function transfer_new_collections()
    {
        $oldid = $this->request->request('oldid');
        $newid = $this->request->request('newid');
        $iscustom = Db::name('fedition_accounturl')
            ->where('id', $newid)
            ->find();
        $transfer_collections = Db::name('transfer_collections')
            ->where('accounturl', $oldid)
            ->where('status', 'normal')
            ->select();
        $data = array();
        if (!empty($transfer_collections)) {
            foreach ($transfer_collections as $vcollection) {
                $url = $iscustom['shopifyname'] . "/admin/api/2021-10/custom_collections.json";
                $custom_collection['id'] = $vcollection['collection_id'];
                $custom_collection['handle'] = $vcollection['handle'];
                $custom_collection['title'] = $vcollection['title'];
                $custom_collection['updated_at'] = $vcollection['updated_at'];
                $custom_collection['body_html'] = $vcollection['body_html'];
                $custom_collection['published_at'] = $vcollection['published_at'];
                $custom_collection['sort_order'] = $vcollection['sort_order'];
                $custom_collection['template_suffix'] = $vcollection['template_suffix'];
                $custom_collection['published_scope'] = $vcollection['published_scope'];
                $custom_collection['admin_graphql_api_id'] = $vcollection['admin_graphql_api_id'];
                $images['created_at'] = $vcollection['updated_at'];
                $images['src'] = $vcollection['image'];
                $custom_collection['image'] = $images;
                $post['custom_collection'] = $custom_collection;
                if (!empty($custom_collection['id'])) {
                    $data = $this->posturl($url, $post, $iscustom);
                    if ($data) {
                        $data = json_decode($data, true);
                    }
                }
            }
        }
        $this->success('操作成功', $data);
    }

    /**
     * 
     * @param array params
     */
    public function custom_collections_product()
    {
        $id = $this->request->request('id');
        $result = array();
        if (!empty($id)) {
            $iscustom = Db::name('fedition_accounturl')
                ->where('id', $id)
                ->find();
            $url = $iscustom['shopifyname'] . "/admin/api/2021-10/collections/274880659490/products.json";
            $limit = '250';
            $url = $url . '?limit=' . $limit;
            $data = $this->geturl($url, $iscustom['shopifyapikey'], $iscustom['shopifysecretapikey']);
            if ($data) {
                $data = json_decode($data, true);
                if (!empty($data['errors'])) {
                    return $data['errors'];
                }
                $products2 = $data['products'];
                if (!empty($products2)) {
                    foreach ($products2 as $k => $v) {
                        $row['product_id'] = $v['id'];
                    }
                }
                dump($data);
                die;
            }
        }
        $this->success('操作成功', $result);
    }

    /**
    3.  获取 自定义页面
     */
    public function transfer_custom_page()
    {
        $id = $this->request->request('id');
        $result = array();
        if (!empty($id)) {
            $iscustom = Db::name('fedition_accounturl')
                ->where('id', $id)
                ->find();
            if ($iscustom) {
                $result = $this->custom_page_isnormal($iscustom);
            }
        }
        $this->success('操作成功', $result);
    }

    public function custom_page_isnormal($iscustom)
    {
        $url = $iscustom['shopifyname'] . "/admin/api/2021-10/pages.json";
        $limit = '250';
        $url = $url . '?limit=' . $limit;
        $data = $this->geturl($url, $iscustom['shopifyapikey'], $iscustom['shopifysecretapikey']);
        $result = array();
        if ($data) {
            $data = json_decode($data, true);
            if (!empty($data['errors'])) {
                return $data['errors'];
            }
            $custom_collections = $data['pages'];
            if (is_array($custom_collections) && !empty($custom_collections)) {
                //获取主题跟资产
                foreach ($custom_collections as $custom_collection) {
                    $transfer_collections = Db::name('transfer_page')->where('page_id', $custom_collection['id'])->find();
                    if (empty($transfer_collections)) {
                        $arr = array();
                        $arr['accounturl'] = $iscustom['id'];
                        $arr['page_id'] = $custom_collection['id'];
                        $arr['title'] = $custom_collection['title'];
                        $arr['shop_id'] = $custom_collection['shop_id'];
                        $arr['handle'] = $custom_collection['handle'];
                        $arr['body_html'] = $custom_collection['body_html'];
                        $arr['created_at'] = $custom_collection['created_at'];
                        $arr['updated_at'] = $custom_collection['updated_at'];
                        $arr['published_at'] = $custom_collection['published_at'];
                        $arr['template_suffix'] = $custom_collection['template_suffix'];
                        $arr['admin_graphql_api_id'] = $custom_collection['admin_graphql_api_id'];
                        $arr['createtime'] = time();
                        $arr['updatetime'] = time();
                        $result = Db::name('transfer_page')->insert($arr);
                    }
                }
            }
        }
        return $result;
    }

    /**
    转移
     */
    public function transfer_new_page()
    {
        $oldid = $this->request->request('oldid');
        $newid = $this->request->request('newid');
        $iscustom = Db::name('fedition_accounturl')
            ->where('id', $newid)
            ->find();
        $transfer_collections = Db::name('transfer_page')
            ->where('accounturl', $oldid)
            ->where('status', 'normal')
            ->select();
        $data = array();
        if (!empty($transfer_collections)) {
            foreach ($transfer_collections as $vcollection) {
                $url = $iscustom['shopifyname'] . "/admin/api/2021-10/pages.json";
                $custom_collection['id'] = $vcollection['page_id'];
                $custom_collection['handle'] = $vcollection['handle'];
                $custom_collection['title'] = $vcollection['title'];
                $custom_collection['shop_id'] = $vcollection['shop_id'];
                $custom_collection['created_at'] = $vcollection['created_at'];
                $custom_collection['updated_at'] = $vcollection['updated_at'];
                $custom_collection['body_html'] = $vcollection['body_html'];
                $custom_collection['published_at'] = $vcollection['published_at'];
                $custom_collection['template_suffix'] = $vcollection['template_suffix'];
                $custom_collection['admin_graphql_api_id'] = $vcollection['admin_graphql_api_id'];
                $post['page'] = $custom_collection;
                if (!empty($custom_collection['id'])) {
                    $data = $this->posturl($url, $post, $iscustom);
                    if ($data) {
                        $data = json_decode($data, true);
                    }
                }
            }
        }
        $this->success('操作成功', $data);
    }

    /**
     * 资产
     * attachment base64 编码的图像。
    checksum 表示，由 32 个十六进制数字组成的字符串。如果资产最近未更新，则可能为 null。
    content_type 表示，由资产的类型和子类型组成。
    key 主题中资产的路径。它由文件的目录和文件名组成。例如，资产assets/bg-body-green.gif在资产目录中，因此其键是assets/bg-body-green.gif.
    public_url 资产的面向公众的 URL。
    size 资产大小（以字节为单位）。
    value 资产的文本内容，例如模板文件的 HTML 和 Liquid 标记。
     */
    public function transfer_themes_asset($arr, $iscustom)
    {
        $url = $iscustom['shopifyname'] . "/admin/api/2021-10/themes/" . $arr['theme_id'] . "/assets.json";
        $data = $this->geturl($url, $iscustom['shopifyapikey'], $iscustom['shopifysecretapikey']);
        $result = array();
        if ($data) {
            $data = json_decode($data, true);
            if (!empty($data['errors'])) {
                return $data['errors'];
            }
            $assets = $data['assets'];
            if (is_array($assets) && !empty($assets)) {
                //获取主题跟资产
                Db::name('transfer_themes_asset')
                    ->where('theme_id', $arr['theme_id'])
                    ->delete();
                foreach ($assets as $asset) {
                    $arr2['theme_id'] = $arr['theme_id'];
                    $arr2['created_at'] = $asset['created_at'];
                    $arr2['updated_at'] = $asset['updated_at'];
                    $arr2['attachment'] = isset($asset['attachment']) ? $asset['attachment'] : '';
                    $arr2['checksum'] = isset($asset['checksum']) ? $asset['checksum'] : '';
                    $arr2['content_type'] = isset($asset['content_type']) ? $asset['content_type'] : '';
                    $arr2['key'] = isset($asset['key']) ? $asset['key'] : '';
                    $arr2['public_url'] = isset($asset['public_url']) ? $asset['public_url'] : '';
                    $arr2['size'] = isset($asset['size']) ? $asset['size'] : '';
                    $arr2['value'] = isset($asset['value']) ? $asset['value'] : '';
                    $arr2['checksum'] = isset($asset['checksum']) ? $asset['checksum'] : '';
                    $arr2['createtime'] = time();
                    $arr2['updatetime'] = time();
                    $result = Db::name('transfer_themes_asset')->insert($arr2);
                }
            }
        }
        return $result;
    }

    //转移资产
    public function transfer_new_asset()
    {
        $oldtheme_id = $this->request->request('oldtheme_id');
        $newtheme_id = $this->request->request('newtheme_id');

        $transfer_themes = Db::name('transfer_themes')
            ->where('theme_id', $newtheme_id)
            ->find();
        $iscustom = Db::name('fedition_accounturl')
            ->where('id', $transfer_themes['accounturl'])
            ->find();
        $data = array();
        if (!empty($transfer_themes)) {
            $transfer_themes_asset = Db::name('transfer_themes_asset')
                ->where('theme_id', $oldtheme_id)
                ->where('status', 'normal')
                ->where('content_type', 'video/mp4')
                ->limit(25)
                ->order('id desc')
                ->select();
            if (!empty($transfer_themes_asset)) {
                foreach ($transfer_themes_asset as $vtheme) {
                    $url = $iscustom['shopifyname'] . "/admin/api/2021-10/themes/" . $newtheme_id . "/assets.json";
                    $asset = array();
                    $asset['key'] = $vtheme['key'];
                    $asset['public_url'] = $vtheme['public_url'];
                    $asset['created_at'] = $vtheme['created_at'];
                    $asset['updated_at'] = $vtheme['updated_at'];
                    $asset['content_type'] = $vtheme['content_type'];
                    $asset['size'] = $vtheme['size'];
                    $asset['checksum'] = $vtheme['checksum'];
                    $asset['theme_id'] = $newtheme_id;
                    $post['asset'] = $asset;
                    $data = $this->puturl($url, $post, $iscustom);
                    if ($data) {
                        $data = json_decode($data, true);
                        if (!empty($data['errors'])) {
                            $arr['status'] = 'hidden';
                        } else {
                            $arr['status'] = 'imported';
                        }
                    } else {
                        $arr['status'] = 'hidden';
                    }
                    Db::name('transfer_themes_asset')
                        ->where('id', $vtheme['id'])
                        ->update($arr);
                }
            } else {
                $this->success('暂无可导数据');
            }
        }
        $this->success('操作成功', $data);
    }

    function geturl($url, $apikey, $secretapikey)
    {
        $headerArray = array("Content-Type:application/json;", 'Authorization:Basic ' . base64_encode("$apikey:$secretapikey"));
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArray);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }

    public function posturl($url, $data = array(), $iscustom = null)
    {
        $data = (is_array($data)) ? json_encode($data, JSON_UNESCAPED_UNICODE) : $data;
        $apikey = $iscustom['shopifyapikey'];
        $secretapikey = $iscustom['shopifysecretapikey'];

        $headerArray = array("Content-Type:application/json;", 'Authorization:Basic ' . base64_encode("$apikey:$secretapikey"));
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headerArray);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

    public function puturl($url, $data = array(), $iscustom = null)
    {
        $data = (is_array($data)) ? json_encode($data, JSON_UNESCAPED_UNICODE) : $data;
        $apikey = $iscustom['shopifyapikey'];
        $secretapikey = $iscustom['shopifysecretapikey'];

        $headerArray = array("Content-Type:application/json;", 'Authorization:Basic ' . base64_encode("$apikey:$secretapikey"));
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headerArray);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT"); //设置请求方式
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }


    //批量处理商品转换到店铺
    public function product_to_shopify()
    {
        //获取产品id集合   1,2,3
        $products_id = $this->request->request('products_id');
        //店铺地址
        $shopify_url = $this->request->request('shopify_url');
        if (empty($products_id) || empty($shopify_url)) {
            $this->error('参数错误');
        }
        //解析相关id
        $arr_ids = explode(',', $products_id);
        $arr = ['products_id' => $arr_ids, 'shopify_url' => $shopify_url];
        $job = "addons\aqueue\library\jobs\ProductToShopify";
        $queue = "ProductToShopify";
        Queue::push($job, $arr, $queue);
        $this->success('操作成功');
    }
}
